<template>
  <div class="block">

    <div id="app">
      <div class="search-container">
        <div class="search-box">
          <div class="label">标题或内容</div>
          <el-input v-model="searchText" placeholder="请输入搜索内容"></el-input>
        </div>
        <div class="date-picker">
          <div class="label">时间范围</div>
          <el-date-picker v-model="dateRange" type="daterange" unlink-panels="" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" @change="validateDateRange"></el-date-picker>
        </div>
        <div class="option-selector">
          <div class="label">新闻或动态</div>
          <el-select v-model="selectedOption" placeholder="请选择新闻或动态" class="wide-select">
            <el-option v-for="option in options" :key="option.value" :label="option.label"
              :value="option.value"></el-option>
          </el-select>
        </div>
        <el-button type="danger" class="button primary" @click="loadData">搜索</el-button>
        <el-button type="danger" class="button1 primary" @click="dialogVisible = true">新增</el-button>
      </div>
    </div>

    <div>
      <el-dialog class="add" title="新增动态或新闻" :visible.sync="dialogVisible">
        <el-form :model="form" :rules="rules" ref="form" label-width="80px">
          <el-form-item label="作者" prop="author">
            <el-input style="width: 400px;" v-model="form.author"></el-input>
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input style="width: 400px;"  type="textarea" v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="日期" prop="date">
            <el-input style="width: 400px;" v-model="form.date"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="label">
            <el-select v-model="form.label" placeholder="请选择新闻或动态" class="wide-select">
              <el-option v-for="option in options" :key="option.value" :label="option.label"
                :value="option.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="链接" prop="url">
            <el-input style="width: 400px;" v-model="form.url"></el-input>
          </el-form-item>
          <el-form-item label="内容"  prop="content">
            <el-input style="width: 400px;" type="textarea" v-model="form.content"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>

    </div>

    <el-table :data="comtableData" show-header>
      <el-table-column prop="author" width="150px" label="作者">
      </el-table-column>
      <el-table-column prop="title" width="200px" label="标题">
      </el-table-column>
      <el-table-column prop="label" width="120px" label="类型">
        <template slot-scope="scope">
          <span v-if="scope.row.label === 0">新闻</span>
          <span v-if="scope.row.label === 1">活动</span>
        </template>
      </el-table-column>
      <el-table-column prop="date" width="100px" label="日期">
      </el-table-column>
      <el-table-column prop="image" label="图片">
        <template slot-scope="scope">
          <img :src="scope.row.image" style="width: 300px;height:200px" />
        </template>
      </el-table-column>
      <el-table-column prop="url" width="200px" label="文章链接">
      </el-table-column>
      <el-table-column prop="content" width="400px" label="内容">
        <template slot-scope="scope">
          <!-- 使用 truncate 过滤器截断文本 -->
          {{ scope.row.content | truncate }}
        </template>
      </el-table-column>
      <el-table-column width="100px" label="操作">
        <template slot-scope="scope">
          <el-button size="small" type="danger" @click="handleEdit(scope.row)">修改</el-button>
          <div style="margin-top:10px">
            <el-button size="small" type="danger" @click="deletehandleEdit(scope.row)">删除</el-button>
          </div>

          <el-upload class="upload-demo" ref="uploadImg" action="api/news/upload" :headers="headers"
            :data="uploadParams" accept="image/jpg,image/jpeg" :on-error="handleError" :limit="limitNum"
            :on-exceed="handleExceed" :on-success="handleSuccess1" :before-upload="handleBeforeUpload"
            style="margin-top:10px">
            <el-button size="small" type="danger" @click="handleUpload(scope.row)">图片上传</el-button>
          </el-upload>
          <!-- :file-list="fileList" -->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog label="编辑任务信息" :visible.sync="eddialogVisible">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="70px">
        <el-form-item label="作者" prop="author">
          <el-input style="width: 400px;" v-model="editForm.author"></el-input>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input style="width: 400px;"  type="textarea" v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-input style="width: 400px;" v-model="editForm.date"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="label">
          <el-select v-model="editForm.label" placeholder="请选择新闻或动态" class="wide-select">
            <el-option v-for="option in options" :key="option.value" :label="option.label"
              :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="选择图片" prop="image">
          <el-input style="width: 400px;" v-model="editForm.image" />
        </el-form-item> -->

        <el-form-item label="链接" prop="url">
          <el-input style="width: 400px;" v-model="editForm.url"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input style="width: 700px; "  type="textarea" v-model="editForm.content"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="eddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>


      </div>
    </el-dialog>

    <!-- <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5,10,15,30,60]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination> -->
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'App',
  inject: ['reload'],
  data() {
    return {
      headers: {
        'token': 'Bearer initial'
      },
      uploadParams: {
        id: null
      },
      limitNum: 1,
      searchText: '',
      dateRange: ['', ''],
      beginTime: "",
      endTime: "",
      selectedOption: '',
      options: [
        { value: '0', label: '新闻' },
        { value: '1', label: '活动' },
        // { value: 'option3', label: '选项3' },
      ],
      comtableData: [],
      date: '',
      page: 1,
      pageSize: 15,
      search: '',
      dialogVisible: false,
      eddialogVisible: false,
      deleteTask: false,
      form: {
        author: '',
        title: '',
        date: '',
        image: '',
        label: '',
        url: '',
        // image: this.selectedFile
      },
      editForm: {},
      rules: {
        author: [
          { required: true, message: '请输入作者名', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        date: [
          { required: true, message: '请输入日期：20xx-0x-xx', trigger: 'blur' }
        ],
        url: [
          { required: false, message: '请输入链接', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
      }

    }

  },
  created() {
    this.loadData();
    this.headers['token'] = `Bearer ${this.$getToken()}`;
  },
  methods: {
    convertTimestamp(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      // const hours = String(date.getHours()).padStart(2, '0');
      // const minutes = String(date.getMinutes()).padStart(2, '0');
      // const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} `;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val
      this.page = 1
      this.loadData()

    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val
      this.loadData()
    },

    validateDateRange(value) {
      console.log(value);
      this.beginTime = new Date(value[0]).toISOString().split('T')[0];
      this.endTime = new Date(value[1]).toISOString().split('T')[0];
      if (value && value.length === 2 && value[0] && value[1]) {
        if (value[0] <= value[1]) {
          // 开始日期小于等于结束日期，可以进行查询
          this.dateRangeIsValid = true;
        } else {
          // 开始日期大于结束日期，可以在这里提示用户或重置日期范围
          this.$message.error('结束日期应该晚于开始日期');
          this.dateRange = [value[1], value[1]]; // 重置为相同日期
          this.dateRangeIsValid = false;
        }
      }
    },
    // onSearch() {
    //   if (this.dateRangeIsValid) {
    //     this.loadData(this.dateRange);
    //   } else {
    //     this.$message.info('请选择一个有效的时间范围');
    //   }
    // },
    loadData() {
      // 找到selectedOption对应的选项对象
      const selectedOptionObj = this.options.find(option => option.value === this.selectedOption);
      const query = {
        pageNo: this.page,
        pageSize: this.pageSize,
        beginTime: this.beginTime, // 开始日期
        endTime: this.endTime, // 结束日期
        label: selectedOptionObj ? selectedOptionObj.value : null, // 使用三元运算符确保label不为undefined
        title: this.searchText,
        content: this.searchText
      };
      axios.get(`api/news/page`, { params: query }).then((res) => {
        console.log(res.data.list);
        const convertedList = res.data.list.map(item => {
          return {
            ...item,
            date: this.convertTimestamp(item.date) // 转换日期
          };
        });
        this.comtableData = convertedList
        this.total = res.data.total
      }).catch((error) => {
        console.error(error);
        this.$message.error('错误')
      });
    },
    submitForm() {
      if (!this.form.author) {
        this.$message.error('作者名不能为空');
        return;
      }
      // 检查 title 字段是否为空
      if (!this.form.content) {
        this.$message.error('内容不能为空');
        return;
      }
      // 检查 title 字段是否为空
      if (!this.form.title) {
        this.$message.error('标题不能为空');
        return;
      }
      if (!this.form.label) {
        this.$message.error('类型不能为空');
        return;
      }
      const datePattern = /^\d{4}-\d{2}-\d{2}$/;
      if (!this.form.date) {
        this.$message.error('日期不能为空');
        return;
      }
      if (!datePattern.test(this.form.date)) {
        this.$message.error('日期格式不正确，应为 YYYY-MM-DD');
        return;
      }
      axios.post(`api/news/save`, this.form).then((res) => {
        console.log(res);
        if (res.status == '200') {
          this.dialogVisible = false
          this.$message.success('新增成功')
          this.reload()
        } else {
          console.log('error submit!!')
          return false
        }
      })


    },


    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(() => {
          done();
        })
        .catch(() => { });
    },
    cancelDelete() {
      this.deleteTask = false;
    },
    confirmDelete() {
      let selectedIds = this.comtableData.map((item) => item.taskid);

      // 在这里发送删除全部数据的请求
      this.$confirm('此操作将删除所有数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        axios.delete(`http://121.37.242.119:8080/tasks/delete?selectedIds=${selectedIds}`).then((res) => {
          console.log(res.data.code);
          // Vue.set(this.form,this.selectedIds.openid,null);
          // Vue.set(this.form, 'openid', null);
          if (res.data.code == 1) {
            this.deleteTask = false;
            this.$message.success('删除成功')
            this.reload()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleEdit(row) {
      this.editForm = { ...row }; // 创建编辑表单的数据副本
      this.eddialogVisible = true; // 显示对话框


      // this.selectedFile = null;
    },
    saveEdit() {
      axios.put(`api/news/update`, this.editForm).then((res) => {

        console.log(res);
        // 在这里处理保存编辑后的数据
        console.log('保存编辑后的数据:', this.editForm);
        if (res.status == '200') {
          this.eddialogVisible = false; // 关闭对话框
          this.$message.success('修改信息成功')
          this.reload()
        } else {
          this.$message.success('修改信息失败，请联系开发者')
          return false
        }
      });
    },
    deleteAllData() {
      // 在这里编写发送删除请求的代码
      // 例如使用 Axios 发送 HTTP 删除请求
      axios.get(`http://121.37.242.119:8080/admin/company/delete`),
        // 假设删除成功
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      this.deleteTask = false;
      this.reload()
    },

    deletehandleEdit(row) {
      if (row.id != null) {
        let id = row.id;
        if (id == null) {
          this.$message.error('请选择需要删除的员工。')
        } else {
          axios.delete(`api/news/delete/${id}`).then((res) => {
            console.log(res);
            this.$message.success('删除成功')
            this.reload()
          })
        }
      } else {
        this.$message.error('请先选择需要删除的员工。');
      }
      console.log(row);
      console.log(row.taskid);
    },

    // 照片文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$notify.warning({
        title: '警告',
        message: `只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`
      })
    },
    // 上传照片文件之前的钩子
    handleBeforeUpload(file) {
      console.log(file.type)
      if (!(file.type === 'image/jpg' || file.type === 'image/jpeg')) {
        this.$notify.warning({
          title: '警告',
          message: '请上传格式为image/jpg的图片'
        })
      }
      // const size = file.size / 1024 / 1024
      // if (size > 1) {
      //   this.$notify.warning({
      //     title: '警告',
      //     message: '图片大小必须小于1M'
      //   })
      // }
    },
    handleSuccess1() {
      this.dialogImageUrl = ''
      this.reload()
      this.$notify({
        title: '恭喜',
        message: '添加图片成功',
        type: 'success',
        duration: 5000
      })
    },
    // 上传图片
    handleUpload(row) {
      this.uploadParams.id = row.id
      console.log(row);
      const token = localStorage.getItem('token'); // 确保这个函数返回有效的token
      this.headers = {
        'Authorization': `Bearer ${token}`
      };
    },

  }
}
</script>

<style>
.search-container {
  margin-bottom: 20px;
}

#app {
  /* font-family: Avenir, Helvetica, Arial, sans-serif; */
  font-family: PingFangSC-Medium;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  background-color: #fff;
  color: #606266;
  border-radius: 20px;
}

.search-container {

  display: flex;
  justify-content: center;
  align-items: center;


}

.search-container>div {
  margin-right: 70px;
  margin-bottom: 20px;
}

.label {
  margin-top: 30px;
  text-align: left;
  margin-bottom: 20px;
  font-weight: bold;

}

.button {
  font-family: PingFangSC-Medium;
  width: 90px;
  height: 50px;
  background: #f27657;
  border-radius: 20px;
}

.button1 {
  font-family: PingFangSC-Medium;
  width: 90px;
  height: 50px;
  background: #f3a895;
  border-radius: 20px;
}

.button:hover {
  background: #F16440;
  border: 0;
}
</style>